/*
 * I write in my free time, for personal using
 * when i fell proud of it, i will give it to public
 * now,have nothing more to say
 */
package com.quangtin3.utils;

/**
 * utils collection, some i write my self, and some borrow from
 * jpos: hexStrign
 * wildCard: modifyed version from  codeproject by quandv & me
 * @author quanghx
 */
public class Utils {

    public static byte[] getByte(int i) {
        byte[] b = new byte[4];
        int[] n = new int[4];
        n[3] = (i % 256);
        n[2] = ((i - n[3]) / 256);
        n[1] = ((((i - n[3]) / 256) - n[2]) / 256);
        n[0] = ((((((i - n[3]) / 256) - n[2]) / 256) - n[1]) / 256);

        for (int k = 0; k < 4; k++) {
            b[k] = (byte) (n[k] & 0xff);
        }
        return b;
    }

    public static int getInt(byte[] b) throws TunllException {
        if (b.length == 4) {
            int[] n = new int[4];
            for (int i = 0; i < 4; i++) {
                n[i] = (b[i] & 0xff);
            }
            return (n[3] + n[2] * 256 + n[1] * 256 * 256 + n[0] * 256 * 256 * 256);
        } else {
            throw new TunllException("unsupported input array other than 2,4");
        }
    }

    /**
     * converts a byte array to hex string 
     * (suitable for dumps and ASCII packaging of Binary fields
     * @param b - byte array
     * @return String representation
     */
    public static String hexString(byte[] b) {
        StringBuffer d = new StringBuffer(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            char hi = Character.forDigit((b[i] >> 4) & 0x0F, 16);
            char lo = Character.forDigit(b[i] & 0x0F, 16);
            d.append(Character.toUpperCase(hi));
            d.append(Character.toUpperCase(lo));
        }
        return d.toString();
    }

    public static String getHost(String add) throws TunllException {
        int i = add.indexOf(':');
        if (i > 0) {
            return (add.substring(0, i)).trim();
        }
        throw new TunllException("getHost error");
    }

    public static int getPort(String add) throws TunllException {
        int i = add.indexOf(':');
        try {
            if (i > 0) {
                return Integer.parseInt((add.substring(i+1)).trim());
            }
        } catch (NumberFormatException e) {
            throw new TunllException(e);
        }
        throw new TunllException("getPort error");
    }
}
